//
//  YYRAlertController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2019/7/3.
//  Copyright © 2019 优房网. All rights reserved.
//

#import "YYRAlertController.h"

//toast默认展示时间
static NSTimeInterval const YYRAlertShowDurationDefault = 1.0f;

#pragma mark - I.AlertActionModel
@interface YYRAlertActionModel : NSObject
@property (nonatomic, copy) NSString * title;
@property (nonatomic, assign) UIAlertActionStyle style;
@end
@implementation YYRAlertActionModel

- (instancetype)init {
    if (self = [super init]) {
        self.title = @"";
        self.style = UIAlertActionStyleDefault;
    }
    return self;
}

@end



#pragma mark - II.YYRAlertController
/**
 AlertActions配置
 
 @param actionBlock YYRAlertActionBlock
 */
typedef void (^YYRAlertActionsConfig)(YYRAlertActionBlock actionBlock);


@interface YYRAlertController ()

//YYRAlertActionModel数组
@property (nonatomic, strong) NSMutableArray <YYRAlertActionModel *>* yyr_alertActionArray;
//是否操作动画
@property (nonatomic, assign) BOOL yyr_setAlertAnimated;
//action配置
- (YYRAlertActionsConfig)alertActionsConfig;

@end

@implementation YYRAlertController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.alertDidDismiss) {
        self.alertDidDismiss();
    }
}
- (void)dealloc {
    //    NSLogFunc; #define NSLogFunc NSLog(@"=====Begin==========\n FILE: %@\n FUNC: %s\n LINE: %d\n", [NSString stringWithUTF8String:__FILE__].lastPathComponent, __PRETTY_FUNCTION__, __LINE__)

}

#pragma mark - Private
//action-title数组
- (NSMutableArray<YYRAlertActionModel *> *)yyr_alertActionArray {
    if (_yyr_alertActionArray == nil) {
        _yyr_alertActionArray = [NSMutableArray array];
    }
    return _yyr_alertActionArray;
}
//action配置
- (YYRAlertActionsConfig)alertActionsConfig {
    return ^(YYRAlertActionBlock actionBlock) {
        if (self.yyr_alertActionArray.count > 0) {
            //创建action
            __weak typeof(self)weakSelf = self;
            
            [self.yyr_alertActionArray enumerateObjectsUsingBlock:^(YYRAlertActionModel *actionModel, NSUInteger idx, BOOL * _Nonnull stop) {
                UIAlertAction *alertAction = [UIAlertAction actionWithTitle:actionModel.title style:actionModel.style handler:^(UIAlertAction * _Nonnull action) {
                    __strong typeof(weakSelf)strongSelf = weakSelf;
                    if (actionBlock) {
                        actionBlock(idx, action, strongSelf);
                    }
                }];
                //可利用这个改变字体颜色，但是不推荐！！！
                //                [alertAction setValue:[UIColor grayColor] forKey:@"titleTextColor"];
                //action作为self元素，其block实现如果引用本类指针，会造成循环引用
                [weakSelf addAction:alertAction];
            }];
        } else {
            NSTimeInterval duration = self.toastStyleDuration > 0 ? self.toastStyleDuration : YYRAlertShowDurationDefault;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:!(self.yyr_setAlertAnimated) completion:NULL];
            });
        }
    };
}

#pragma mark - Public

- (instancetype)initAlertControllerWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle {
    if (!(title.length > 0) && (message.length > 0) && (preferredStyle == UIAlertControllerStyleAlert)) {
        title = @"";
    }
    
    self = [[self class] alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    
    if (!self) return nil;
    
    self.yyr_setAlertAnimated = NO;
    self.toastStyleDuration = YYRAlertShowDurationDefault;
    
    return self;
}


- (void)alertAnimateDisabled {
    self.yyr_setAlertAnimated = YES;
}


#pragma mark - addButton

- (YYRAlertActionTitle)addActionDefaultTitle {
    // 该block返回值不是本类属性，只是局部变量，不会造成循环引用
    return ^(NSString *title) {
        YYRAlertActionModel *actionModel = [[YYRAlertActionModel alloc] init];
        actionModel.title = title;
        actionModel.style = UIAlertActionStyleDefault;
        [self.yyr_alertActionArray addObject:actionModel];
        return self;
    };
}

- (YYRAlertActionTitle)addActionCancelTitle {
    return ^(NSString *title) {
        YYRAlertActionModel *actionModel = [[YYRAlertActionModel alloc] init];
        actionModel.title = title;
        actionModel.style = UIAlertActionStyleCancel;
        [self.yyr_alertActionArray addObject:actionModel];
        return self;
    };
}

- (YYRAlertActionTitle)addActionDestructiveTitle {
    return ^(NSString *title) {
        YYRAlertActionModel *actionModel = [[YYRAlertActionModel alloc] init];
        actionModel.title = title;
        actionModel.style = UIAlertActionStyleDestructive;
        [self.yyr_alertActionArray addObject:actionModel];
        return self;
    };
}

@end



#pragma mark - III.UIViewController扩展
@implementation UIViewController (YYRAlertController)

- (void)yyr_showAlertWithPreferredStyle:(UIAlertControllerStyle)preferredStyle title:(NSString *)title message:(NSString *)message appearanceProcess:(YYRAlertAppearanceProcess)appearanceProcess actionsBlock:(YYRAlertActionBlock)actionBlock {
    if (appearanceProcess) {
        YYRAlertController *alertMaker = [[YYRAlertController alloc] initAlertControllerWithTitle:title message:message preferredStyle:preferredStyle];
        //防止nil
        if (!alertMaker) {
            return ;
        }
        //加工链
        if (appearanceProcess) appearanceProcess(alertMaker);
        //配置响应
        alertMaker.alertActionsConfig(actionBlock);
        
        [self presentViewController:alertMaker animated:!(alertMaker.yyr_setAlertAnimated) completion:^{
            if (alertMaker.alertDidShown) alertMaker.alertDidShown();
        }];
    }
}

- (void)yyr_showAlertWithTitle:(NSString *)title message:(NSString *)message appearanceProcess:(YYRAlertAppearanceProcess)appearanceProcess actionsBlock:(YYRAlertActionBlock)actionBlock {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self yyr_showAlertWithPreferredStyle:UIAlertControllerStyleAlert title:title message:message appearanceProcess:appearanceProcess actionsBlock:actionBlock];
    });
}

- (void)yyr_showActionSheetWithTitle:(NSString *)title message:(NSString *)message appearanceProcess:(YYRAlertAppearanceProcess)appearanceProcess actionsBlock:(YYRAlertActionBlock)actionBlock {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self yyr_showAlertWithPreferredStyle:UIAlertControllerStyleActionSheet title:title message:message appearanceProcess:appearanceProcess actionsBlock:actionBlock];
    });
}


@end

@implementation UIAlertController (YYR)

/**
 YYRAlertController: show-alert(iOS8)
 
 @param title             title
 @param message           message
 @param appearanceProcess alert配置过程
 @param actionBlock       alert点击响应回调
 */
+ (void)yyr_showAlertWithTitle:(nullable NSString *)title
                      message:(nullable NSString *)message
            appearanceProcess:(YYRAlertAppearanceProcess)appearanceProcess
                 actionsBlock:(nullable YYRAlertActionBlock)actionBlock NS_AVAILABLE_IOS(8_0) {
    [[UIWindow yyr_currentViewController] yyr_showAlertWithTitle:title message:message appearanceProcess:appearanceProcess actionsBlock:actionBlock];
}

/**
 YYRAlertController: show-actionSheet(iOS8)
 
 @param title             title
 @param message           message
 @param appearanceProcess actionSheet配置过程
 @param actionBlock       actionSheet点击响应回调
 */
+ (void)yyr_showActionSheetWithTitle:(nullable NSString *)title
                            message:(nullable NSString *)message
                  appearanceProcess:(YYRAlertAppearanceProcess)appearanceProcess
                       actionsBlock:(nullable YYRAlertActionBlock)actionBlock NS_AVAILABLE_IOS(8_0) {
    [[UIWindow yyr_currentViewController] yyr_showActionSheetWithTitle:title message:message appearanceProcess:appearanceProcess actionsBlock:actionBlock];
}

@end
